//SamXIAO
#include <bits/stdc++.h>
using namespace std;

#define szARR_CNT_OF(x) sizeof(x) / sizeof(x[0])
#define TO_BOOL(x, mask) (x & mask) != 0
#if 0
#define DBG_PRINT printf
#else
#define DBG_PRINT
#endif
#define XY_N 300
struct xy_t {
   int x, y;
   xy_t(){};
   xy_t(int x, int y) : x(x), y(y) {}
};

int n, m;
char a[XY_N][XY_N];
int ans[XY_N][XY_N];
xy_t xyFr, xyTo;
queue<xy_t> q;

void init() {
   memset(a, 0, sizeof(a));
   memset(ans, 0, sizeof(ans));
}

void dump() {
   DBG_PRINT("\n");
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) DBG_PRINT("%c", a[i][j]);
      DBG_PRINT("\n");
   }
   DBG_PRINT(" =============\n");
}

inline bool isIn(xy_t xy) { return 0 <= xy.x && xy.x < n && 0 <= xy.y && xy.y < m; }

void bfs(xy_t xy) {
   if (!isIn(xy) || '.' != a[xy.x][xy.y]) return;
   a[xy.x][xy.y] = '#';
   q.push(xy);
   while (!q.empty()) {
      xy_t p = q.front();
      q.pop();
      int dxy[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
      for (int i = 0; i < szARR_CNT_OF(dxy); i++) {
         int nx = p.x + dxy[i][0], ny = p.y + dxy[i][1];
         if (isIn(xy_t(nx, ny)) && '.' == a[nx][ny]) {
            a[nx][ny] = '#';
            ans[nx][ny] = ans[p.x][p.y] + 1;
            q.push(xy_t(nx, ny));
         }
      }
   }
}

void work1() {
   int t;
   scanf("%d%", &t);
   while (t--) {
      init();
      scanf("%d%d", &n, &m);
      for (int i = 0; i < n; i++) scanf("%s", a[i]);

      xy_t fr, to;
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < m; j++) {
            if ('S' == a[i][j]) fr.x = i, fr.y = j;
            if ('E' == a[i][j]) to.x = i, to.y = j;
         }
      }
      a[fr.x][fr.y] = a[to.x][to.y] = '.';
      bfs(fr);
      ans[to.x][to.y] ? printf("%d\n", ans[to.x][to.y]) : printf("oop!\n");
   }
}

int main() {
   work1();
   return 0;
}